package cn.edu.seu.herald.informationplatform.filter;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.edu.seu.herald.informationplatform.bean.league.Album;
import cn.edu.seu.herald.informationplatform.bean.league.Linked;
import cn.edu.seu.herald.informationplatform.dao.database.AlbumDao;

public class LeagueAlbumsRequired implements Filter {

	private static final String ALBUMS_ID = "albums";
	
	private static List<Linked<Album>> parseToLinkedAlbums(
				Map<Integer, Album> albumMapping, int leagueId) {
		LinkedAlbumAdapter adapter =
				LinkedAlbumAdapter.getInstance();
		List<Linked<Album>> activities =
				adapter.adapt(albumMapping);
		return activities;
	}

	@Override
	public void init(FilterConfig config) throws ServletException {}

	@Override
	public void destroy() {}

	@Override
	public void doFilter(ServletRequest request,
			ServletResponse response, FilterChain chain)
					throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		
		int leagueId = getLeagueId(httpRequest);
		try {
			AlbumDao access = AlbumDao.getDao();
			Map<Integer, Album> albumMapping = access.getAlbumsByLeagueId(
					leagueId);
			List<Linked<Album>> albums =
					parseToLinkedAlbums(albumMapping, leagueId);
			request.setAttribute(ALBUMS_ID, albums);
		} catch (SQLException e) {
			httpResponse.sendError(404, "league albums required");
			return;
		}
		
		chain.doFilter(request, response);
	}
	
	private int getLeagueId(HttpServletRequest httpRequest) {
		String leagueIdParam = httpRequest.getParameter(
				LeagueSpecified.PARAM_NAME_OF_LEAGUE_ID);
		return Integer.parseInt(leagueIdParam);
	}

}
